<?php
require_once(dirname(__FILE__)."/../include/common.inc.php");	
$dsql = new DedeSql(false);
$row = $dsql->GetOne("SELECT * FROM `#@__weixin` WHERE id=1");
$TOKEN = $row['TOKEN'];
$msg = $row['msg'];
$searchrx=$row['searchrx'];
$menurx=$row['menurx'];
define("TOKEN", $TOKEN);
$x=strpos($msg,"}")+1;
$msg1 = substr($msg,0,strrpos($msg,'{'));  
$msg2 = substr($msg,$x);  
define("msg1",$msg1);
define("msg2",$msg2);
define("searchrx",$searchrx);
define("menurx",$menurx);
$wechatObj = new wechatCallback();
$wechatObj->valid();

class wechatCallback
{
    private $items = '';
    private $articleCount = 0;
    private $keyword = '';
	public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
        	echo $echoStr;
            $this->responseMsg();
        	exit;
        }
    }

    public function responseMsg()
    {
	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
	$fromUsername = $postObj->FromUserName;
	$toUsername = $postObj->ToUserName;
	$RX_TYPE = trim($postObj->MsgType);
	$time = time();
	$textTpl = "<xml>
				<ToUserName><![CDATA[".$fromUsername."]]></ToUserName>
				<FromUserName><![CDATA[".$toUsername."]]></FromUserName>
				<CreateTime>".$time."</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				<FuncFlag>0</FuncFlag>
				</xml>";     
	$picTpl = "<xml>
				<ToUserName><![CDATA[".$fromUsername."]]></ToUserName>
				<FromUserName><![CDATA[".$toUsername."]]></FromUserName>
				<CreateTime>".$time."</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<Content><![CDATA[]]></Content>
				<ArticleCount>%d</ArticleCount>
				<Articles>%s</Articles>
				<FuncFlag>1</FuncFlag>
				</xml>";	
				
if (!empty($postStr)){
	switch($RX_TYPE){
		   case "text":
		   		$this->keyword = strtolower($postObj->Content);//接收用户消息
		  		$messtype=1;
		  		break;
           case "event":
                $this->keyword = $this->handleEvent($postObj);
				$messtype=0;
                break;
           default:
                $resultStr = "Unknow msg type: ".$RX_TYPE;
				$messtype=0;
                break;
     }


	if($this->keyword == 'hi' || $this->keyword == '您好'  || $this->keyword == '你好' ||$this->keyword == 'hello2bizuser' ){
	   $contentStr = "请发送您想知道的内容！";//自定义欢迎回复;
       echo sprintf($textTpl, $contentStr);
       }else if(!empty( $this->keyword )){
               if ($messtype){
				   $this->rx_search();
			   }else{
				   $this->m_search();
			   }
               
			   if($this->articleCount == 0){
                  $contentStr = msg1."{$this->keyword}".msg2;
                  echo sprintf($textTpl, $contentStr);
               }else{
                  echo sprintf($picTpl,$this->articleCount,$this->items);
               }
      }
				
				

        }else {
        	echo "";
        	exit;
        }
    }

private function handleEvent($object)
    {
        switch ($object->Event)
        {
            case "subscribe":
                $this->keyword = "关注时回复";
                break;
		    case "CLICK": 
		        $this->keyword =$object->EventKey;
                break;
            default :
                $this->keyword = "Unknow Event: ".$object->Event;
                break;
        }
        return $this->keyword;
}

private function rx_search(){//根据用户回复的内容模糊搜索文章
global $dsql;
$weixin_posts = $dsql->SetQuery("Select * From `#@__archives` where title like '%".$this->keyword."%' order by id desc LIMIT 0, 5");
//按文章权重排序
$items = '';
$dsql->Execute();

while($weixin_post=$dsql->GetObject()){        
$title =$weixin_post->title;
$excerpt = $weixin_post->description ;//获取摘要
$thumb = $weixin_post->litpic ;//获取缩略图;
$link = '/plus/view.php?aid='.$weixin_post->id;
$items = $items . $this->get_item($title, $excerpt, $thumb, $link);   
$this->articleCount++;     
}

if($this->articleCount > searchrx) $this->articleCount = searchrx;
$this->items = $items;
}


private function m_search(){//菜单事件按栏目名精确搜索
global $dsql;
$weixin_posts = $dsql->SetQuery("Select  `#@__archives`.id,`#@__archives`.title,`#@__archives`.description,`#@__archives`.litpic,`#@__archives`.typeid,`#@__archives`.weight from `#@__archives` INNER JOIN `#@__arctype` ON `#@__archives`.typeid = `#@__arctype`.id where `#@__arctype`.typename = '".$this->keyword."' order by weight desc LIMIT 10");
//按文章权重排序
$items = '';
$dsql->Execute();

while($weixin_post=$dsql->GetObject()){        
$title =$weixin_post->title;
$excerpt = $weixin_post->description;//获取摘要
$thumb = $weixin_post->litpic ;//获取缩略图;
$link = '/plus/view.php?aid='.$weixin_post->id;
$items = $items . $this->get_item($title, $excerpt, $thumb, $link);   
$this->articleCount++;     
}

if($this->articleCount > menurx) $this->articleCount = menurx;
$this->items = $items;
}

private function get_item($title, $description, $picUrl, $url){
if(!$description) $description = $title;
return
'
<item>
<Title><![CDATA['.$title.']]></Title>
<Description><![CDATA['.$description.']]></Description>
<PicUrl><![CDATA[http://'.$_SERVER['HTTP_HOST'].$picUrl.']]></PicUrl>
<Url><![CDATA[http://'.$_SERVER['HTTP_HOST'].$url.']]></Url>
</item>
';
}

private function checkSignature(){
$signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
}

}
?>